package com.zhangh.summer.admin.support.util;

import lombok.extern.slf4j.Slf4j;

import javax.servlet.http.HttpServletRequest;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.net.UnknownHostException;
import java.util.Enumeration;

/**
 * @description: TODO
 * @author: zhanghui  zhanghlucky@163.com
 * @create: 2021-10-12 11:19
 **/
@Slf4j
public class IpGetter {

        /**
         * 获取request ip
         * @param request 请求
         * @return ip
         */
        public static String getRequestIp(HttpServletRequest request) {
            String ip = request.getHeader("X-Forwarded-For");
            if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
                ip = request.getHeader("Proxy-Client-IP");
            }
            if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
                ip = request.getHeader("WL-Proxy-Client-IP");
            }
            if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
                ip = request.getHeader("HTTP_CLIENT_IP");
            }
            if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
                ip = request.getHeader("HTTP_X_FORWARDED_FOR");
            }
            if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
                ip = request.getRemoteAddr();
                if (ip.equals("127.0.0.1")|| ip.endsWith("0:0:0:0:0:0:1")) {
                    InetAddress inet = null;
                    try {
                        inet = InetAddress.getLocalHost();
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    assert inet != null;
                    ip = inet.getHostAddress();
                }
            }
            return ip;
        }

        /**
         * 获取mac地址
         * @param ip ip
         * @return mac
         */
        public static String getMACAddress(String ip) {
            String line;
            String macAddress = "";
            final String MAC_ADDRESS_PREFIX = "MAC Address = ";
            final String LOOPBACK_ADDRESS = "127.0.0.1";
            try {
                if (LOOPBACK_ADDRESS.equals(ip)) {
                    InetAddress inetAddress = InetAddress.getLocalHost();
                    byte[] mac = NetworkInterface.getByInetAddress(inetAddress).getHardwareAddress();
                    StringBuilder sb = new StringBuilder();
                    for (int i = 0; i < mac.length; i++) {
                        if (i != 0) {
                            sb.append("-");
                        }
                        String s = Integer.toHexString(mac[i] & 0xFF);
                        sb.append(s.length() == 1 ? 0 + s : s);
                    }
                    macAddress = sb.toString().trim().toUpperCase();
                    return macAddress;
                }
            }catch (Exception e){
                log.error("get mac address error:{}",e.getMessage());
                e.printStackTrace();
            }

            try {
                Process p = Runtime.getRuntime().exec("nbtstat -A " + ip);
                InputStreamReader isr = new InputStreamReader(p.getInputStream());
                BufferedReader br = new BufferedReader(isr);
                while ((line = br.readLine()) != null) {
                    int index = line.indexOf(MAC_ADDRESS_PREFIX);
                    if (index != -1) {
                        macAddress = line.substring(index + MAC_ADDRESS_PREFIX.length()).trim().toUpperCase();
                    }
                }
                br.close();
            } catch (IOException e) {
                log.error("get mac address error:{}",e.getMessage());
                e.printStackTrace();
            }
            return macAddress;
        }

        public static String getLocalIP() throws UnknownHostException {
            if (isWindowsOS()) {
                return InetAddress.getLocalHost().getHostAddress();
            } else {
                return getLinuxLocalIp();
            }
        }

        /**
         * 判断操作系统是否是Windows
         *
         * @return  是否win
         */
        public static boolean isWindowsOS() {
            boolean isWindowsOS = false;
            String osName = System.getProperty("os.name");
            if (osName.toLowerCase().contains("windows")) {
                isWindowsOS = true;
            }

            return isWindowsOS;
        }

        /**
         * 获取本地Host名称
         */
        public static String getLocalHostName() throws UnknownHostException {
            return InetAddress.getLocalHost().getHostName();
        }

        /**
         * 获取Linux下的IP地址
         *
         * @return IP地址
         */
        private static String getLinuxLocalIp() {
            String ip = "";

            try {
                for (Enumeration<NetworkInterface> en = NetworkInterface.getNetworkInterfaces(); en.hasMoreElements();) {
                    NetworkInterface intf = en.nextElement();
                    String name = intf.getName();
                    if (!name.contains("docker") && !name.contains("lo")) {
                        for (Enumeration<InetAddress> enumIpAddr = intf.getInetAddresses(); enumIpAddr.hasMoreElements();) {
                            InetAddress inetAddress = enumIpAddr.nextElement();
                            if (!inetAddress.isLoopbackAddress()) {
                                String ipaddress = inetAddress.getHostAddress();
                                if (!ipaddress.contains("::") && !ipaddress.contains("0:0:") && !ipaddress.contains("fe80")) {
                                    ip = ipaddress;
                                }
                            }
                        }
                    }
                }
            } catch (SocketException ex) {
                log.error("get linux ip error:{}", ex.getMessage());
                ip = "127.0.0.1";
            }
            return ip;
        }
    }

